package com.base.forum.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import cn.mysteel.util.ObjectUtils;

import com.base.forum.dao.ForumDAO;
import com.base.forum.entity.Forum;
import com.base.forum.service.ForumService;
import com.mysteel.page.Page;

@Service("forumService")
public class ForumServiceImpl implements ForumService
{

	@Autowired
	private ForumDAO forumDao;
	
	@Override
	public String Create(Forum forum)
	{
		Assert.notNull (forum);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put ("name" ,forum.getName ());
		List<Long> list = forumDao.query (params);
		if(ObjectUtils.notNull (list)&&ObjectUtils.notEmpty (list))
		{
			
			return "已经存在相同或相似的社区,创建失败!";
		}
		
		int count = forumDao.count (null);
		if(count == 0)
		{
			forum.setId (10000);
		}
		forumDao.save (forum);
		
		return "恭喜,"+forum.getName ()+"创建成功!";
	}

	@Override
	public Forum getById(long id)
	{
		
		return forumDao.get (id);
	}

	@Override
	public void update(Forum forum)
	{
		Assert.notNull (forum);
		
		Forum f = forumDao.get (forum.getId ());
		if(ObjectUtils.notNull (f))
		{
			f.setLabel (forum.getLabel ());
			f.setMemberId (forum.getMemberId ());
			f.setNumOfInvatation (forum.getNumOfInvatation ());
			f.setNumOfMember (forum.getNumOfMember ());
			
			forumDao.update (f);
		}
		
	}

	@Override
	public Page<Forum> query(Map<String, Object> params, int currentPageNum,int maxPageRowCount)
	{
		Page<Forum> page = null;
		if (ObjectUtils.isNull(params))
		{
			params = new HashMap<String, Object>(2);
		}
		
		int count = forumDao.count(params);
		if (count > 0)
		{
			page = new Page<Forum>();
			page.setTotalRowCount(count);
			page.setCurrentPageNum(currentPageNum);
			page.setMaxPageRowCount(maxPageRowCount);
			page.setURL(params);
			params.put("startPageRowCount", page.getStartPageRowCount());
			params.put("maxPageRowCount", page.getMaxPageRowCount());

			List<Long> ForumIds = forumDao.query(params);

			if (ObjectUtils.notEmpty(ForumIds))
			{
				List<Forum> Forums = new ArrayList<Forum>(ForumIds.size());

				for (long ForumsId : ForumIds)
				{
					Forums.add(getById (ForumsId));
				}

				page.setDatas(Forums);
			}
		}

		return page;
	}
}
